﻿using B.MES.SLY.Service;
using B.MES.SLY.Service.Input.WorkStation;
using B.MES.SLY.Service.OutPut;
using ClosedXML.Excel;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using Standard;
using Yitter.IdGenerator;

namespace B.MES.SLY.API.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class WorkStationController : ControllerBase
    {
        private readonly IMesService _mesService;

        public WorkStationController(IMesService mesService)
        {
            _mesService = mesService;
        }
        private static int serialNumber = 1; // 静态变量，用于记录流水号，初始为1
        /// <summary>
        /// 编码（流水号）
        /// </summary>
        /// <param name="codeType"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet]
        public string GetCode()
        {
            var result = new ApiResult<string>();
            //查询数据的数量 工位数量
            var count = _mesService.GetWorkStationCount().ResultData.Count;
            var serialNumber = count + 1;
            string serialPart = serialNumber.ToString("D7");
            string code = "JNZG-GW" + DateTime.Now.ToString("yyyyMMddHH") + serialPart;
            serialNumber++;
            return code;

        }
        /// <summary>
        /// 工位新增
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPost]
        public ApiResult<int> AddWorkStation(AddWorkStationInput input)
        {
            input.WORKSTATION_CODE = GetCode();
            return _mesService.AddWorkStation(input);
        }
        /// <summary>
        /// 工位修改
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPut]
        public ApiResult<int> UpdateWorkStation(UpdateWorkStationInput input)
        {
            return _mesService.UpdateWorkStation(input);
        }
        /// <summary>
        /// 工位删除
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        [HttpPut]
        public ApiResult<int> DeleteWorkStation(string ID)
        {
           return _mesService.DeleteWorkStation(ID);
        }
        /// <summary>
        /// 工位列表显示
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ApiResult<List<GetWorkStationOutPut>> GetWorkStation()
        {
            return _mesService.GetWorkStation();
        }
        /// <summary>
        /// 查询所有工位分页列表查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet]
        public ApiPaging<GetWorkStationOutPut> GetPageWorkStation([FromQuery]SearchWorkStationInput input)
        {
            return _mesService.GetPageWorkStation(input);
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="Ids"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpDelete]
        public ApiResult<int> WorkStationDeleteList(string Ids)
        {
            return _mesService.WorkStationDeleteList(Ids.Split(",").ToList());
        }
        ///<summary>
        /// 导出客户管理数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("export")]
        public IActionResult Export()
        {
            // 查询所有未删除的数据
            var data = _mesService.GetWorkStation().ResultData;

            if (data == null || !data.Any())
            {
                return NotFound(new ApiResult<string>
                {
                    Code = ApiCode.NotFound,
                    Message = "没有可导出的数据"
                });
            }

            // 创建Excel文件
            using (var workbook = new XLWorkbook())
            {
                var worksheet = workbook.Worksheets.Add("客户管理");

                // 设置表头
                worksheet.Cell(1, 1).Value = "序号";
                worksheet.Cell(1, 2).Value = "编码";
                worksheet.Cell(1, 3).Value = "名称";
                worksheet.Cell(1, 4).Value = "产线名称";
                worksheet.Cell(1, 5).Value = "创建时间";
                worksheet.Cell(1, 6).Value = "更新时间";

                // 填充数据
                for (int i = 0; i < data.Count; i++)
                {
                    worksheet.Cell(i + 2, 1).Value = data[i].ID;
                    worksheet.Cell(i + 2, 2).Value = data[i].WORKSTATION_CODE;
                    worksheet.Cell(i + 2, 3).Value = data[i].WORKSTATION_NAME;
                    worksheet.Cell(i + 2, 4).Value = data[i].WORKSTATION_DESCRIPTION;

                    worksheet.Cell(i + 2, 5).Value = data[i].CREATETIME?.ToString("yyyy-MM-dd HH:mm:ss");
                    worksheet.Cell(i + 2, 6).Value = data[i].UPDATETIME?.ToString("yyyy-MM-dd HH:mm:ss");
                }

                // 设置响应内容类型
                Response.ContentType = "application/vnd.openxmlformats-     officedocument.spreadsheetml.sheet";
                Response.Headers.Add("Content-Disposition", "attachment;        filename=WorkshopManagement.xlsx");

                using (var stream = new MemoryStream())
                {
                    workbook.SaveAs(stream);
                    return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                "WorkshopManagement.xlsx");
                }
            }
        }
    }
}
